import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_chat_ui/utils/audio_utils.dart';
import 'package:flutter_chat_ui/views/chat_bottom_widgets/voice_controller.dart';
import 'package:get/get_state_manager/get_state_manager.dart';

///
/// 波浪组件
///
class WaveView extends StatefulWidget {
  const WaveView({
    super.key,
  });

  @override
  State<WaveView> createState() => _WaveViewState();
}

class _WaveViewState extends State<WaveView> {
  final List<double> _waveHeights = List.generate(12, (index) => 0.3);
  Timer? _waveTimer;
  late final ValueNotifier<List<double>> _waveHeightsNotifier;

  @override
  void initState() {
    super.initState();
    _waveHeightsNotifier = ValueNotifier(_waveHeights);
    // 执行波浪
    _waveTimer = Timer.periodic(const Duration(milliseconds: 150), (timer) {
      // 创建新的列表来存储更新后的波浪高度
      List<double> newWaveHeights = [];
      for (int i = 0; i < _waveHeights.length; i++) {
        newWaveHeights.add(0.2 + Random().nextDouble() * 0.8);
      }
      _waveHeightsNotifier.value = newWaveHeights;
    });
  }

  @override
  void dispose() {
    super.dispose();
    _waveTimer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return GetX<VoiceController>(
      builder: (controller) {
        bool isCanceling = controller.voiceStatus.value == VoiceStatus.cancelSend;

        return CustomPaint(
          painter: WaveBgArrowPainter(isCanceling: isCanceling),
          child: Container(
            width: 125,
            height: 65,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              color: isCanceling ? Colors.red : const Color(0xff89ED5E),
            ),
            child: Center(
              child: ValueListenableBuilder<List<double>>(
                valueListenable: _waveHeightsNotifier,
                builder: (context, value, child) => WaveVerLineView(waveHeights: value),
              ),
            ),
          ),
        );
      },
    );
  }
}

///
/// 波浪竖线小组件
///
class WaveVerLineView extends StatelessWidget {
  final List<double> waveHeights;

  const WaveVerLineView({
    super.key,
    required this.waveHeights,
  });

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.end,
      children: waveHeights.map((height) {
        return Container(
          width: 2,
          height: 20 * height,
          margin: const EdgeInsets.symmetric(horizontal: 2),
          decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.circular(2),
          ),
        );
      }).toList(),
    );
  }
}

///
/// 绘制向下箭头
///
class WaveBgArrowPainter extends CustomPainter {
  final bool isCanceling;

  const WaveBgArrowPainter({
    this.isCanceling = false,
  });

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()..color = isCanceling ? Colors.red : const Color(0xff89ED5E);

    Path path = Path();
    path.moveTo(size.width * 0.5 - 12, size.height);
    path.lineTo(size.width * 0.5, size.height + 10);
    path.lineTo(size.width * 0.5 + 12, size.height);
    path.close();
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant WaveBgArrowPainter oldDelegate) => isCanceling != oldDelegate.isCanceling;
}
